package com.ihcil.forecast.demo.filters;

import com.alibaba.fastjson.JSON;
import com.ihcil.forecast.demo.vo.RespBean;
import com.ihcil.forecast.demo.vo.RespBeanEnum;
import com.sun.prism.impl.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author WYQ
 * @version 1.0
 */
//@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;

    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1 获取本次url
        String requestURI = request.getRequestURI();

        log.info("拦截到路径：{}", requestURI);

        // 2 判断本次请求是否需要处理
        // 放行的url
        String[] urls = new String[] {
                "/login/toLogin",
                "/login/doLogin",
                "/login/toRegist",
                "**.jpg",
                "**.map",
                "/favicon.ico"
        };

        if(check(urls, requestURI)) {
            log.info("本次请求不需要拦截：{}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //4 判断登录状态
        String ticket = (String) request.getSession().getAttribute("userTicket");
        if(ticket == null) {
            response.getWriter().write(JSON.toJSONString(RespBean.error(RespBeanEnum.UNVALIDUSER_ERROR)));
            return;
        }

        // 进入redis查看用户是否处于登录状态（Redis缓存是否失效）
        if(redisTemplate.hasKey(ticket) != null) {
            log.info("用户已登录，用户id为:{}", request.getSession().getAttribute("userTicket"));
            filterChain.doFilter(request, response);
            return;
        }

        // 5 未登录，返回登录状态即可，前端有拦截器。通过输出流的方式
        response.getWriter().write(JSON.toJSONString(RespBean.error(RespBeanEnum.UNVALIDUSER_ERROR)));
        return;

    }

    // 检查是否放行
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }


}
